package com.doge.walknovel.business.reader

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.doge.wnpro.R
import com.doge.walknovel.api.model.NovelDetailInfo
import com.doge.walknovel.api.model.ChapterInfo
import com.doge.walknovel.api.model.TextInfo
import com.doge.walknovel.business.reader.viewholders.*
import com.doge.walknovel.core.base.adapters.BasePagedAdapter
import com.doge.walknovel.core.base.adapters.MoreLoadingVH
import com.doge.walknovel.core.base.adapters.NoMoreVH
import com.doge.walknovel.utils.inflate

const val RECORD_CHAPTER = "recordChapter"
const val UNLOCK = "unlock"


class ReaderAdapter : BasePagedAdapter() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ItemType.Text -> TextViewHolder(parent, callback)
            ItemType.ChaptersTitle -> ChapterTitleViewHolder(parent, callback)
            ItemType.Locked -> LockedViewHolder(parent, callback)
            ItemType.NovelCover -> NovelCoverViewHolder(parent, callback)
            ItemType.PreLoading ->  MoreLoadingVH(parent.inflate(R.layout.cell_reader_pre_loading))
            com.doge.walknovel.core.base.adapters.ItemType.NoMorePlaceHolder -> NoMoreVH(parent.inflate(R.layout.cell_reader_no_more))
            else -> super.onCreateViewHolder(parent, viewType)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val item = getItem(position)
        when (holder) {
            is TextViewHolder -> item?.data<TextInfo>()?.let { holder.bind(it) }
            is LockedViewHolder -> item?.data<ChapterInfo>()?.let { holder.bind(it) }
            is ChapterTitleViewHolder -> item?.data<ChapterInfo>()?.let { holder.bind(it) }
            is NovelCoverViewHolder -> item?.data<NovelDetailInfo>()?.let { holder.bind(it) }
        }
    }

    override fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder) {
        super.onViewAttachedToWindow(holder)
        if (holder is ChapterTitleViewHolder) {
            val chapterInfo = (holder.itemView.tag as? ChapterInfo?)
            callback.invoke(RECORD_CHAPTER, chapterInfo)
        } else if (holder is LockedViewHolder) {
            val chapterInfo = (holder.itemView.tag as? ChapterInfo?)
            callback.invoke(RECORD_CHAPTER, chapterInfo)
        }
    }
}